package _26define;


import java.io.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;


public class Demo2 {
    public static void main(String[] args) throws IOException {
        String sourcePath1 = "src/note/a.txt";
        String targetPath1 = "src/note/copya.txt";
        //String sourcePath2 = "String time1=fileCopyTask1.get();";
        String targetPath2 = "src/note/copyb.txt";
        //String sourcePath3 = "src/note/c.txt";
        String targetPath3 = "src/note/copyc.txt";
        FutureTask<String> fileCopyTask1 = new FutureTask<>(new FileCopyTask(sourcePath1,targetPath1));
        FutureTask<String> fileCopyTask2 = new FutureTask<>(new FileCopyTask(sourcePath1,targetPath2));
        FutureTask<String> fileCopyTask3 = new FutureTask<>(new FileCopyTask(sourcePath1,targetPath3));
        new Thread(fileCopyTask1).start();
        new Thread(fileCopyTask2).start();
        new Thread(fileCopyTask3).start();
        try {
            String time1=fileCopyTask1.get();
            String time2=fileCopyTask1.get();
            String time3=fileCopyTask1.get();
            System.out.println(time1);
            System.out.println(time2);
            System.out.println(time3);
            FileWriter fileWriter=new FileWriter("src/note/b.txt");
            fileWriter.write(time1+"ms");
            fileWriter.write(time2+"ms");
            fileWriter.write(time3+"ms");
            fileWriter.flush();
            fileWriter.close();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }
}
class FileCopyTask implements Callable<String> {
    private String sourcePath;
    private String targetPath;


    public FileCopyTask(String sourcePath, String targetPath) {
        this.sourcePath = sourcePath;
        this.targetPath = targetPath;
    }


    @Override
    public String call() {
        long oldTime=System.currentTimeMillis();
        try {
            FileInputStream in=new FileInputStream(sourcePath);
            FileOutputStream out=new FileOutputStream(targetPath);
            double allBytes= in.available();
            byte[] bytes=new byte[128];
            int bytesRead;
            long totalBytesCopied=0;
            //System.out.println(in.available());
            while ((bytesRead=in.read(bytes))!=-1){
                out.write(bytes,0,bytesRead);
                totalBytesCopied+=bytesRead;
                double progress=(double) totalBytesCopied/allBytes*100;
                System.out.println(sourcePath+"文件已复制"+progress+"%");
            }
            in.close();
            out.close();
            System.out.println(sourcePath+"文件已复制完成");
        } catch (IOException e) {
            e.printStackTrace();
        }
        long nowTime=System.currentTimeMillis();
        String a=""+(nowTime-oldTime);
        return a;
    }
}
